import type { App } from "vue";
import { umsAdmin } from "../request/http";

import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  RouteRecordRaw,
} from "vue-router";

import { useAdminStoreWithOut } from "../store/modules/admin";
const adminStore = useAdminStoreWithOut();
// RouteRecordRaw[]，routes的类型
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/login/index.vue"),
  },
  {
    path: "/homepage",
    name: "homepage",
    component: () => import("../pages/home/index.vue"),
  },
  // {
  //   path: "/pms",
  //   name: "pms",
  //   component: () => import("../pages/home/index.vue"),
  //   children: [
  //     {
  //       path: "product",
  //       name: "product",
  //       component: () => import("../pages/pms/product/index.vue"),
  //     },
  //   ],
  // },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 前置导航守卫
router.beforeEach(async (to, from, next) => {
  // token && menu.length===0
  const token = localStorage.getItem("token");
  console.log(adminStore.menus.length);

  if (token && adminStore.menus.length === 0) {
    //发请求
    const adminData = await umsAdmin.getAdminInfo();
    if (adminData.code === 200) {
      adminStore.updateMenus(adminData.data.menus);
      // 生成动态路由规则
      const newMenus = adminStore.genNewMenus;
      for (let key in newMenus) {
        let menuObj: RouteRecordRaw = {
          path: "/" + newMenus[key].name,
          name: newMenus[key].name,
          component: () => import("../pages/home/index.vue"),
          children: [],
        };
        newMenus[key].children.forEach((submenu) => {
          menuObj.children?.push({
            path: submenu.name,
            name: submenu.name,
            component: () =>
              import(
                `../pages/${newMenus[key].name}/${submenu.name}/index.vue`
              ),
          });
        });
        // 添加到路由里面
        router.addRoute(menuObj);
      }
      router.addRoute({
        path: "/",
        name: "home",
        redirect: "/index",
        component: () => import("../pages/home/index.vue"),
        children: [
          {
            path: "index",
            name: "index",
            component: () => import("../pages/index/index.vue"),
          },
        ],
      });
      // 重定向到即将跳转的路由
      return next(to);
    } else {
      // 删掉token,重定向到login
      localStorage.clear();
      return next("/login");
    }
  } else if (token && to.path === "/login") {
    return next(from);
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else {
    return next();
  }
});

// 这里的APP是vue里面的一种类型，需要声明，而app要与main.js里面的app类型一致。因为initRouter是作为方法传出来给main.js调用的,appz这里作为形参
export function initRouter(app: App<Element>) {
  app.use(router);
}
